#!/usr/bin/env python2
#-*-encoding:utf8-*-

import Polygon,Polygon.IO,Polygon.Utils


def catch_data(in_file):
    """
    open file,and extract datas into dict format.
    like {tid:(True,((1,2;2,3;4,5;...),(32,12;45,65;...)))}
    """
    pset = dict()
    with open(in_file,'r') as sf:
        multi = False
        for line in sf:
            columns = line.strip().split('|')
            if columns[3] == '0':
                multi = False
                try:
                    tid = columns[2]
                    pset[tid] = (multi,columns[-1])
                except Exception,e:
                    pset[tid] = "('','')"
                    print e

            elif columns[3] == '1':
                multi = True
                tid = columns[2]
                try:
                    pset[tid] = (multi,columns[-1].split('&&'))
                except Exception,e:
                    print 'invalid tag.',e
                    print line
                    pset[tid] = "('','')"
    return pset


def p_isinside(xi,yi,src_polys):
    """
    method to find id(s) which (xi,yi) located.
    """
    ##print len(src_polys)
    point = dict()
    _keyset = set()
    for keys in src_polys.iterkeys():
        ##print src_polys[keys][0]
        x_set = set()
        if  src_polys[keys][0] == False:
            """
            situation that contains one polygon.
            """
            ##print  src_polys[keys][1].split(';')
            for p in src_polys[keys][1].split(';'):
                x,y =  p.split(',')
                ##print x,y
                x_set.add((float(x),float(y)))    
            ##print tuple(x_set)
           
            #create Polygon instance.
            pg = Polygon.Polygon(tuple(x_set))
            #pg_fill = Polygon.Utils.fillHoles(pg)
            pg_fill = Polygon.Utils.convexHull(pg)
            p = Polygon.Utils.pointList(pg_fill)
            #Polygon.IO.writeSVG('data/'+keys+'.svg', (tuple(x_set),))
            Polygon.IO.writeSVG('data/'+keys+'.svg', (p,))
 
            #isInside method. core here.
            if pg.isInside(xi,yi):
                ##print (xi,yi),type(keys)
                _keyset.add(keys)
                dictkey =(xi,yi)
                point[dictkey]=_keyset

        elif src_polys[keys][0] == True:
            """
            situation that contains two or more polygons.
            """
            ##print src_polys[keys][1][0]
            n=0
            for mp in src_polys[keys][1][0].split('&'):
                ##print mp
                x_set = set()
                for src_p in mp.split(';'):
                    ##print src_p
                    x,y = src_p.split(',')
                    ##print x,y
                    x_set.add((float(x),float(y)))    
                ##print tuple(x_set)
                ##pg_fill = Polygon.Utils.fillHoles(pg)
                
                """
                Fill area with Convex Hull method. 
                """
                pg_fill = Polygon.Utils.convexHull(pg)
                #unpack polygon.
                p = Polygon.Utils.pointList(pg_fill)
                    
                #draw svg.
                Polygon.IO.writeSVG('data/'+keys+'_'+str(n)+'.svg', (p,))
                n+=1
                _pg = Polygon.Polygon(tuple(x_set))
                     
                if _pg.isInside(xi,yi):
                    ##print (xi,yi),':',type(keys)
                    point[(xi,yi)]=_keyset.add(keys)
    return point 

if __name__ == '__main__':
    src_dict =  catch_data('result_rc.dat')
    print p_isinside(120.590455,31.30841,src_dict) 
